﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace InfoSource.Controllers
{
    public class BaseController : Controller
    {
		protected override void OnActionExecuting(ActionExecutingContext filterContext)
		{
			base.OnActionExecuting(filterContext);
		}

		public ActionResult DynamicView()
		{
			return DynamicView(null);
		}

		public ActionResult DynamicView(object model)
		{
			string action = this.RouteData.GetRequiredString("action");
			return DynamicView(model, action);
		}

		public ActionResult DynamicView(object model, string action)
		{
			string viewType = "full";

			if (HttpContext.Request.Params.AllKeys.Contains("viewtype", StringComparer.OrdinalIgnoreCase))
			{
				viewType = HttpContext.Request.Params["viewtype"];
			}

			switch (viewType)
			{
				default:
				case "full":
					return View(model);
				case "partial":
					Dictionary<string, object> result = RenderPartialViewAsObject(model, action);
					

					return Json(result);
			}
		}

		public Dictionary<string,object> RenderPartialViewAsObject(object model, string action)
		{
			Dictionary<string, object> results = new Dictionary<string, object>();
			string partialPath = !string.IsNullOrEmpty(action) 
									? action 
									: RouteData.GetRequiredString("action");

			this.ViewData.Model = model;
			this.ViewBag.IsPartial = true;

			using (StringWriter sw = new StringWriter())
			{
				ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, partialPath);
				ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);


				// copy model state items to the html helper 
				foreach (var item in viewContext.Controller.ViewData.ModelState)
				{
					if (!viewContext.ViewData.ModelState.Keys.Contains(item.Key))
					{
						viewContext.ViewData.ModelState.Add(item);
					}
				}

				viewResult.View.Render(viewContext, sw);

				 results["html"] = sw.GetStringBuilder().ToString();
				 results["scripts"] = (viewContext.Controller.ViewData.ContainsKey("Scripts") ? viewContext.Controller.ViewData["Scripts"] : new List<string>());
				 results["inlineScripts"] = (viewContext.Controller.ViewData.ContainsKey("InlineScripts") ? viewContext.Controller.ViewData["InlineScripts"] : new List<string>());
				 results["styleSheets"] = (viewContext.Controller.ViewData.ContainsKey("StyleSheets") ? viewContext.Controller.ViewData["StyleSheets"] : new List<string>());
			}

			return results;
		}

    }
}
